package org.wei.db.mongo;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.wei.utils.IOUtil;
import org.wei.utils.exception.LogHelper;

import com.google.gson.Gson;
import com.mongodb.WriteConcern;

public class MongoDbSetting {
	public static boolean isTest = true;
	public static final WriteConcern DEFALTE_WRITE_CONCERN = WriteConcern.JOURNAL_SAFE;
	private static MongoDbSetting instance;

	private List<NetAddress> servers;
	private List<DbCredential> credentials;
	private String dbName;

	private MongoDbSetting() {
	}

	public String getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	public synchronized static MongoDbSetting getInstance() {
		if (instance == null) {
			InputStream is = MongoDbSetting.class
					.getResourceAsStream(getConfigFile());
			String json = null;
			try {
				json = IOUtil.inStream2String(is, "utf-8");
			} catch (UnsupportedEncodingException e) {
				LogHelper.getInstance().error(e);
			}
			Gson gson = new Gson();
			instance = gson.fromJson(json, MongoDbSetting.class);
		}
		return instance;
	}

	public List<NetAddress> getServers() {
		return servers;
	}

	public void setServers(List<NetAddress> servers) {
		this.servers = servers;
	}

	public List<DbCredential> getCredentials() {
		return credentials;
	}

	public void setCredentials(List<DbCredential> credentials) {
		this.credentials = credentials;
	}

	public static String getConfigFile() {
		if (isTest) {
			return "/mongodb-cfg-test.json";
		}
		return "/mongodb-cfg.json";
	}

}
